package yunhe.servlet;

import yunhe.entity.NewsInfo;
import yunhe.entity.UserInfo;
import yunhe.service.NewsServers;
import yunhe.service.impl.NewsServersImpl;
import yunhe.service.impl.UserServersImpl;
import yunhe.util.NewsUtil;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;


@SuppressWarnings("serial")
public class GetNews extends HttpServlet {

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int pageSize = 29; // 一页显示的条数
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		Object o = request.getParameter("currentPage");
		int currentPage;
		NewsServers ns = new NewsServersImpl();
		int pageSum = (int) ((ns.getRowNum() / ((double) pageSize)) + 0.9);
		if (o == null) {
			currentPage = 1;// 当前页码；
		} else {
			currentPage = Integer.parseInt((String) (o));
			if(currentPage<=1){
				currentPage=1;
			}
			if(currentPage>=pageSum){
				currentPage=pageSum;
			}
		}

		List<NewsInfo> lni = ns.getPageBy(pageSize, currentPage);
		HttpSession session=request.getSession();
		session.setAttribute("news", lni);
		session.setAttribute("currentPage",currentPage);//当前页/总页数
		session.setAttribute("pageSum",pageSum);
		String flag=request.getParameter("flag");
		if(flag!=null&&flag.equals("search")){ //带search参数说明时后台查看新闻的请求
			response.sendRedirect(request.getContextPath()+"/admin/searchnews.jsp");  
		}
		else{
			/*
			 * 判断下有无cookie，有直接用cookie登陆
			 */
			Object bs = session.getAttribute("userLoginState");
			if (bs == null) {//第一次进入页面
				Cookie[] cookies = request.getCookies();
				String name = NewsUtil.getValue(cookies, "nuName");
				String pass = NewsUtil.getValue(cookies, "nuPass");
				boolean b = name != "" && pass != ""
						&& (new UserServersImpl().login(name, pass)) > 0;
				if(b){
					session.setAttribute("userLoginState", true);
					session.setAttribute("userInfo", new UserInfo(name));  //cookie登陆成功 写入登陆状态
				}
				else{
					session.setAttribute("userLoginState", null);  //cookie登陆失败
				}
			}
			
			response.sendRedirect(request.getContextPath()+"/index.jsp");
		} 
		
			
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
